<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. 最简单的方式1). 创建一个下载工具类MTDownloaderMTDownloader.h文件1234567#import &amp;lt;Foundation/Foundation.h&amp;gt;@interface MTDownloader : NSObject- (void)download:(NSString *)netUrl;@end">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS-Downloader断点续传">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/iOS/iOS-Downloader断点续传/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. 最简单的方式1). 创建一个下载工具类MTDownloaderMTDownloader.h文件1234567#import &amp;lt;Foundation/Foundation.h&amp;gt;@interface MTDownloader : NSObject- (void)download:(NSString *)netUrl;@end">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-42f511634a28dc33.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T11:00:23.592Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS-Downloader断点续传">
<meta name="twitter:description" content="####1. 最简单的方式1). 创建一个下载工具类MTDownloaderMTDownloader.h文件1234567#import &amp;lt;Foundation/Foundation.h&amp;gt;@interface MTDownloader : NSObject- (void)download:(NSString *)netUrl;@end">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/3110861-42f511634a28dc33.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/iOS/iOS-Downloader断点续传/"/>





  <title>iOS-Downloader断点续传 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/iOS/iOS-Downloader断点续传/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">iOS-Downloader断点续传</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. 最简单的方式<br>1). 创建一个下载工具类MTDownloader<br>MTDownloader.h文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#import &lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">@interface MTDownloader : NSObject</span><br><span class="line"></span><br><span class="line">- (void)download:(NSString *)netUrl;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>MTDownloader.m文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">// 下载，传入下载链接</span><br><span class="line">- (void)download:(NSString *)netUrl &#123;</span><br><span class="line">    NSURL *url = [NSURL URLWithString:netUrl];</span><br><span class="line">    NSURLRequest *request = [NSURLRequest requestWithURL:url];</span><br><span class="line">    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:</span><br><span class="line">     ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) &#123;</span><br><span class="line">         if (connectionError) &#123;</span><br><span class="line">             NSLog(@&quot;连接错误 %@&quot;, connectionError);</span><br><span class="line">             return;</span><br><span class="line">         &#125;</span><br><span class="line">         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;</span><br><span class="line">         if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) &#123;</span><br><span class="line">             // 解析数据</span><br><span class="line">             // 存在的问题，内存暴涨，无法获取下载进度</span><br><span class="line">             [data writeToFile:@&quot;/Users/mazaiting/Desktop/1.zip&quot; atomically:YES];</span><br><span class="line">             NSLog(@&quot;下载成功&quot;);</span><br><span class="line">         &#125; else &#123;</span><br><span class="line">             NSLog(@&quot;服务器内部错误&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这种下载方式存在的问题是下载时内存暴涨，因为文件读取到内存中，并且无法获取下载进度。<br>2). 在ViewController.m文件中使用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;ViewController.h&quot;</span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">@interface ViewController ()</span><br><span class="line"></span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation ViewController</span><br><span class="line"></span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">    [super viewDidLoad];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 触摸屏幕时</span><br><span class="line">- (void)touchesBegan:(NSSet&lt;UITouch *&gt; *)touches withEvent:(UIEvent *)event &#123;</span><br><span class="line">    MTDownloader *downloader = [MTDownloader new];</span><br><span class="line">    [downloader download:@&quot;http://127.0.0.1/HBuilder.zip&quot;];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>####2. 解决获取下载进度问题<br>改造MTDownloader.m文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">// 分类</span><br><span class="line">@interface MTDownloader () &lt;NSURLConnectionDataDelegate&gt;</span><br><span class="line">// 记录文件的总长度,因为在获取下载进度的时候需要文件总长度，所以定义为属性</span><br><span class="line">@property (nonatomic, assign) long long expectedContentLength;</span><br><span class="line">// 记录当前文件的长度</span><br><span class="line">@property (nonatomic, assign) long long currentFileSize;</span><br><span class="line">// 用来记录总共下载的数据</span><br><span class="line">@property (nonatomic, strong) NSMutableData *mutableData;</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloader</span><br><span class="line"></span><br><span class="line">// 懒加载</span><br><span class="line">- (NSMutableData *)mutableData &#123;</span><br><span class="line">    if (_mutableData == nil) &#123;</span><br><span class="line">        _mutableData = [NSMutableData data];</span><br><span class="line">    &#125;</span><br><span class="line">    return _mutableData;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)download:(NSString *)netUrl &#123;</span><br><span class="line">    // 创建url</span><br><span class="line">    NSURL *url = [NSURL URLWithString:netUrl];</span><br><span class="line">    // 创建下载请求</span><br><span class="line">    NSURLRequest *request = [NSURLRequest requestWithURL:url];</span><br><span class="line">    // 设置代理, 实现NSURLConnectionDataDelegate协议</span><br><span class="line">    [[NSURLConnection alloc] initWithRequest:request delegate:self];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#pragma mark- 代理方法</span><br><span class="line">// 接收到响应头</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response &#123;</span><br><span class="line">    NSLog(@&quot;接收到响应 %@&quot;, response);</span><br><span class="line">    // 获取到文件的总长度</span><br><span class="line">    self.expectedContentLength = response.expectedContentLength;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 接收到数据--一点点接收</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data &#123;</span><br><span class="line">    // 将每次接收到的字节长度与已有的文件长度相加</span><br><span class="line">    self.currentFileSize += data.length;</span><br><span class="line">    // 添加接收的数据</span><br><span class="line">    [self.mutableData appendData:data];</span><br><span class="line">    // 当前已下载的文件长度 * 1.0 / 文件的总长度 = 当前的进度</span><br><span class="line">    float process = self.currentFileSize * 1.0 / self.expectedContentLength;</span><br><span class="line">    NSLog(@&quot;接收数据: %f&quot;, process);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载完成</span><br><span class="line">- (void)connectionDidFinishLoading:(NSURLConnection *)connection &#123;</span><br><span class="line">    NSLog(@&quot;下载完成&quot;);</span><br><span class="line">    // 下载完成后将字节数组写入文件</span><br><span class="line">    [self.mutableData writeToFile:@&quot;/Users/mazaiting/Desktop/1.zip&quot; atomically:YES];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载出错</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error &#123;</span><br><span class="line">    NSLog(@&quot;下载出错&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>改造完成后，可以获取下载文件的进度，但仍然后出现内存暴涨的问题。</p>
<p>####3. 解决文件内存暴涨–NSFileHandle/NSOutputStream<br>将第二步中记录下载数据的mutableData属性删除，在此处不再需要，因为是将文件一点一点的写入。<br>在接收一点点接收数据的地方进行数据的存储。</p>
<p>1). NSFileHandle解决<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">// 分类</span><br><span class="line">@interface MTDownloader () &lt;NSURLConnectionDataDelegate&gt;</span><br><span class="line">// 记录文件的总长度,因为在获取下载进度的时候需要文件总长度，所以定义为属性</span><br><span class="line">@property (nonatomic, assign) long long expectedContentLength;</span><br><span class="line">// 记录当前文件的长度</span><br><span class="line">@property (nonatomic, assign) long long currentFileSize;</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloader</span><br><span class="line"></span><br><span class="line">- (void)download:(NSString *)netUrl &#123;</span><br><span class="line">    // 创建url</span><br><span class="line">    NSURL *url = [NSURL URLWithString:netUrl];</span><br><span class="line">    // 创建下载请求</span><br><span class="line">    NSURLRequest *request = [NSURLRequest requestWithURL:url];</span><br><span class="line">    // 设置代理, 实现NSURLConnectionDataDelegate协议</span><br><span class="line">    [[NSURLConnection alloc] initWithRequest:request delegate:self];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#pragma mark- 代理方法</span><br><span class="line">// 接收到响应头</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response &#123;</span><br><span class="line">    NSLog(@&quot;接收到响应 %@&quot;, response);</span><br><span class="line">    // 获取到文件的总长度</span><br><span class="line">    self.expectedContentLength = response.expectedContentLength;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 接收到数据--一点点接收</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data &#123;</span><br><span class="line">    // 将每次接收到的字节长度与已有的文件长度相加</span><br><span class="line">    self.currentFileSize += data.length;</span><br><span class="line">    // 当前已下载的文件长度 * 1.0 / 文件的总长度 = 当前的进度</span><br><span class="line">    float process = self.currentFileSize * 1.0 / self.expectedContentLength;</span><br><span class="line">    NSLog(@&quot;接收数据: %f&quot;, process);</span><br><span class="line">    // 保存数据</span><br><span class="line">    [self saveData:data];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载完成</span><br><span class="line">- (void)connectionDidFinishLoading:(NSURLConnection *)connection &#123;</span><br><span class="line">    NSLog(@&quot;下载完成&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载出错</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error &#123;</span><br><span class="line">    NSLog(@&quot;下载出错&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 保存数据</span><br><span class="line">// data 每次下载的二进制数据</span><br><span class="line">- (void)saveData:(NSData *)data &#123;</span><br><span class="line">    // 保存文件的路径</span><br><span class="line">    NSString *filePath = @&quot;/Users/mazaiting/Desktop/1.zip&quot;;</span><br><span class="line">    // 根据路径获取NSFileHandle, 它不会自动创建文件，而是第0个字节添加数据</span><br><span class="line">    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];</span><br><span class="line">    // 如果fileHandle存在，则让fileHandle的offset偏移量指向文件的末尾，进行数据的添加</span><br><span class="line">    // 如果fileHandle不存在，则创建文件</span><br><span class="line">    if (fileHandle) &#123;</span><br><span class="line">        // fileHandle存在</span><br><span class="line">        // 将文件指针指向文件的末尾</span><br><span class="line">        [fileHandle seekToEndOfFile];</span><br><span class="line">        // 写数据</span><br><span class="line">        [fileHandle writeData:data];</span><br><span class="line">        // 关闭文件</span><br><span class="line">        [fileHandle closeFile];</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // fileHandle不存在</span><br><span class="line">        [data writeToFile:filePath atomically:YES];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>2). NSOutputStream解决<br>流操作时要注意打开流，关闭流，并且要注意初始化流的位置。文件写入时推荐使用流操作。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">// 分类</span><br><span class="line">@interface MTDownloader () &lt;NSURLConnectionDataDelegate&gt;</span><br><span class="line">// 记录文件的总长度,因为在获取下载进度的时候需要文件总长度，所以定义为属性</span><br><span class="line">@property (nonatomic, assign) long long expectedContentLength;</span><br><span class="line">// 记录当前文件的长度</span><br><span class="line">@property (nonatomic, assign) long long currentFileSize;</span><br><span class="line">// NSOutputStream用来保存每次下载的二进制数据</span><br><span class="line">@property (nonatomic, strong) NSOutputStream *outputStream;</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloader</span><br><span class="line"></span><br><span class="line">- (void)download:(NSString *)netUrl &#123;</span><br><span class="line">    // 创建url</span><br><span class="line">    NSURL *url = [NSURL URLWithString:netUrl];</span><br><span class="line">    // 创建下载请求</span><br><span class="line">    NSURLRequest *request = [NSURLRequest requestWithURL:url];</span><br><span class="line">    // 设置代理, 实现NSURLConnectionDataDelegate协议</span><br><span class="line">    [[NSURLConnection alloc] initWithRequest:request delegate:self];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#pragma mark- 代理方法</span><br><span class="line">// 接收到响应头</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response &#123;</span><br><span class="line">    NSLog(@&quot;接收到响应 %@&quot;, response);</span><br><span class="line">    // 获取到文件的总长度</span><br><span class="line">    self.expectedContentLength = response.expectedContentLength;</span><br><span class="line">    // 保存文件的路径</span><br><span class="line">    NSString *filePath = @&quot;/Users/mazaiting/Desktop/1.zip&quot;;</span><br><span class="line">    // 接收到响应头的时候初始化outputStream</span><br><span class="line">    self.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];</span><br><span class="line">    // 打开流</span><br><span class="line">    [self.outputStream open];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 接收到数据--一点点接收</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data &#123;</span><br><span class="line">    // 将每次接收到的字节长度与已有的文件长度相加</span><br><span class="line">    self.currentFileSize += data.length;</span><br><span class="line">    // 当前已下载的文件长度 * 1.0 / 文件的总长度 = 当前的进度</span><br><span class="line">    float process = self.currentFileSize * 1.0 / self.expectedContentLength;</span><br><span class="line">    NSLog(@&quot;接收数据: %f&quot;, process);</span><br><span class="line">    // 保存数据</span><br><span class="line">    [self saveData:data];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载完成</span><br><span class="line">- (void)connectionDidFinishLoading:(NSURLConnection *)connection &#123;</span><br><span class="line">    NSLog(@&quot;下载完成&quot;);</span><br><span class="line">    // 下载完成的时候，关闭流</span><br><span class="line">    [self.outputStream close];&#125;</span><br><span class="line"></span><br><span class="line">// 下载出错</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error &#123;</span><br><span class="line">    NSLog(@&quot;下载出错&quot;);</span><br><span class="line">    // 判断流是否为空，下载出错的时候，关闭流</span><br><span class="line">    if (self.outputStream) &#123;</span><br><span class="line">        [self.outputStream close];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSOutputStream保存数据</span><br><span class="line">// data 每次下载的二进制文件</span><br><span class="line">- (void)saveData:(NSData *)data &#123;</span><br><span class="line">    // 写数据</span><br><span class="line">    [self.outputStream write:data.bytes maxLength:data.length];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSFileHandle保存数据</span><br><span class="line">// data 每次下载的二进制数据</span><br><span class="line">- (void)saveData1:(NSData *)data &#123;</span><br><span class="line">    // 保存文件的路径</span><br><span class="line">    NSString *filePath = @&quot;/Users/mazaiting/Desktop/1.zip&quot;;</span><br><span class="line">    // 根据路径获取NSFileHandle, 它不会自动创建文件，而是第0个字节添加数据</span><br><span class="line">    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];</span><br><span class="line">    // 如果fileHandle存在，则让fileHandle的offset偏移量指向文件的末尾，进行数据的添加</span><br><span class="line">    // 如果fileHandle不存在，则创建文件</span><br><span class="line">    if (fileHandle) &#123;</span><br><span class="line">        // fileHandle存在</span><br><span class="line">        // 将文件指针指向文件的末尾</span><br><span class="line">        [fileHandle seekToEndOfFile];</span><br><span class="line">        // 写数据</span><br><span class="line">        [fileHandle writeData:data];</span><br><span class="line">        // 关闭文件</span><br><span class="line">        [fileHandle closeFile];</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // fileHandle不存在</span><br><span class="line">        [data writeToFile:filePath atomically:YES];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>此时，一个下载的操作工具类就已完成，但目前无法使用断点下载。</p>
<p>####4. 文件的断点下载操作<br> 断点续传思路<br> I. 首先发送一个head请求，获取到服务器文件的大小和名称<br> II. 判断本地文件是否存在<br>      1). 不存在，从0开始下载<br>      2). 存在<br>          a. 本地文件大小 == 服务器文件大小  不需要下载<br>          b. 本地文件大小 &lt; 服务器文件大小   从当前位置下载<br>          c. 本地文件打下 &gt; 服务器文件大小   删除文件，从0下载<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br></pre></td><td class="code"><pre><span class="line">//</span><br><span class="line">// 断点续传思路</span><br><span class="line">// 1. 首先发送一个head请求，获取到服务器文件的大小和名称</span><br><span class="line">// 2. 判断本地文件是否存在</span><br><span class="line">//      1). 不存在，从0开始下载</span><br><span class="line">//      2). 存在</span><br><span class="line">//          a. 本地文件大小 == 服务器文件大小  不需要下载</span><br><span class="line">//          b. 本地文件大小 &lt; 服务器文件大小   从当前位置下载</span><br><span class="line">//          c. 本地文件打下 &gt; 服务器文件大小   删除文件，从0下载</span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">// 分类</span><br><span class="line">@interface MTDownloader () &lt;NSURLConnectionDataDelegate&gt;</span><br><span class="line">// 记录文件的总长度,因为在获取下载进度的时候需要文件总长度，所以定义为属性</span><br><span class="line">@property (nonatomic, assign) long long expectedContentLength;</span><br><span class="line">// 记录当前文件的长度</span><br><span class="line">@property (nonatomic, assign) long long currentFileSize;</span><br><span class="line">// NSOutputStream用来保存每次下载的二进制数据</span><br><span class="line">@property (nonatomic, strong) NSOutputStream *outputStream;</span><br><span class="line">// 文件的存储路径</span><br><span class="line">@property (nonatomic, strong) NSString *filePath;</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloader</span><br><span class="line"></span><br><span class="line">- (void)download:(NSString *)netUrl &#123;</span><br><span class="line">    // 创建url</span><br><span class="line">    NSURL *url = [NSURL URLWithString:netUrl];</span><br><span class="line">    // 获取服务器文件信息, 获取当前文件长度</span><br><span class="line">    [self getServerFileInfo:url];</span><br><span class="line">    // 获取本地文件信息，并且和服务器做比较</span><br><span class="line">    self.currentFileSize = [self getLocalFileInfo];</span><br><span class="line">    // 判断当前文件大小是否是-1，如果是-1，说明文件已经下载完成</span><br><span class="line">    if (self.currentFileSize == -1) &#123;</span><br><span class="line">        NSLog(@&quot;文件已下载完成，请不要重复下载!!!&quot;);</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    // 从指定位置处下载文件</span><br><span class="line">    [self downloadFile: url];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 从指定位置处下载文件</span><br><span class="line">- (void)downloadFile:(NSURL *)url &#123;</span><br><span class="line">    // 创建一个请求</span><br><span class="line">    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];</span><br><span class="line">    // 请求头</span><br><span class="line">    // Range:bytes=x-y 从x个字节下载到y个字节</span><br><span class="line">    // Range:bytes=x-  从x个字节下载到最后</span><br><span class="line">    // Range:bytes=-y  从开始下载到y个字节</span><br><span class="line">    [request setValue:[NSString stringWithFormat:@&quot;bytes=%lld-&quot;, self.currentFileSize] forHTTPHeaderField:@&quot;Range&quot;];</span><br><span class="line">    </span><br><span class="line">    // 设置代理, 实现NSURLConnectionDataDelegate协议</span><br><span class="line">    [[NSURLConnection alloc] initWithRequest:request delegate:self];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 检测本地文件大小</span><br><span class="line">- (long long)getLocalFileInfo &#123;</span><br><span class="line">    // 文件的长度， 如果文件不存在，则为0</span><br><span class="line">    long long fileSize = 0;</span><br><span class="line">    // 获取文件管理者对象</span><br><span class="line">    NSFileManager *fileManager = [NSFileManager defaultManager];</span><br><span class="line">    // 判断文件是否存在</span><br><span class="line">    if ([fileManager fileExistsAtPath:self.filePath]) &#123;</span><br><span class="line">        // 文件存在</span><br><span class="line">        // 获取本地文件的大小</span><br><span class="line">        NSDictionary *attrs = [fileManager attributesOfItemAtPath:self.filePath error:NULL];</span><br><span class="line">        // 赋值</span><br><span class="line">        fileSize = attrs.fileSize;</span><br><span class="line">        // 文件大小等于服务器文件长度</span><br><span class="line">        if (fileSize == self.expectedContentLength) &#123;</span><br><span class="line">            fileSize = -1;</span><br><span class="line">        &#125;</span><br><span class="line">        // 文件大小大于服务器文件长度</span><br><span class="line">        if (fileSize &gt; self.expectedContentLength) &#123;</span><br><span class="line">            fileSize = 0;</span><br><span class="line">            // 删除文件</span><br><span class="line">            [fileManager removeItemAtPath:self.filePath error:NULL];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return fileSize;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 获取服务器文件信息</span><br><span class="line">// 文件的url</span><br><span class="line">- (void)getServerFileInfo:(NSURL *)url &#123;</span><br><span class="line">    // 创建一个请求</span><br><span class="line">    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];</span><br><span class="line">    // 设置请求方法</span><br><span class="line">    request.HTTPMethod = @&quot;head&quot;;</span><br><span class="line">    // 同步请求响应体</span><br><span class="line">    NSURLResponse *response = nil;</span><br><span class="line">    // 发送一个同步请求</span><br><span class="line">    [NSURLConnection sendSynchronousRequest:request returningResponse:&amp;response error:NULL];</span><br><span class="line">    </span><br><span class="line">    // 设置文件的总长度，注意:在下载时- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;方法中为当前文件总长度赋值的语句要删除</span><br><span class="line">    self.expectedContentLength = response.expectedContentLength;</span><br><span class="line">    // 设置文件的存储路径, 存储在临时目录下，拼接文件名</span><br><span class="line">    self.filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:response.suggestedFilename];</span><br><span class="line">    NSLog(@&quot;%@&quot;, self.filePath);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#pragma mark- 代理方法</span><br><span class="line">// 接收到响应头</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response &#123;</span><br><span class="line">    NSLog(@&quot;接收到响应 %@&quot;, response);</span><br><span class="line">    // 接收到响应头的时候初始化outputStream</span><br><span class="line">    self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.filePath append:YES];</span><br><span class="line">    // 打开流</span><br><span class="line">    [self.outputStream open];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 接收到数据--一点点接收</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data &#123;</span><br><span class="line">    // 将每次接收到的字节长度与已有的文件长度相加</span><br><span class="line">    self.currentFileSize += data.length;</span><br><span class="line">    // 当前已下载的文件长度 * 1.0 / 文件的总长度 = 当前的进度</span><br><span class="line">    float process = self.currentFileSize * 1.0 / self.expectedContentLength;</span><br><span class="line">    NSLog(@&quot;接收数据: %f&quot;, process);</span><br><span class="line">    // 保存数据</span><br><span class="line">    [self saveData:data];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载完成</span><br><span class="line">- (void)connectionDidFinishLoading:(NSURLConnection *)connection &#123;</span><br><span class="line">    NSLog(@&quot;下载完成&quot;);</span><br><span class="line">    // 下载完成的时候，关闭流</span><br><span class="line">    [self.outputStream close];&#125;</span><br><span class="line"></span><br><span class="line">// 下载出错</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error &#123;</span><br><span class="line">    NSLog(@&quot;下载出错&quot;);</span><br><span class="line">    // 判断流是否为空，下载出错的时候，关闭流</span><br><span class="line">    if (self.outputStream) &#123;</span><br><span class="line">        [self.outputStream close];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSOutputStream保存数据</span><br><span class="line">// data 每次下载的二进制文件</span><br><span class="line">- (void)saveData:(NSData *)data &#123;</span><br><span class="line">    // 写数据</span><br><span class="line">    [self.outputStream write:data.bytes maxLength:data.length];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSFileHandle保存数据</span><br><span class="line">// data 每次下载的二进制数据</span><br><span class="line">- (void)saveData1:(NSData *)data &#123;</span><br><span class="line">    // 保存文件的路径</span><br><span class="line">    NSString *filePath = @&quot;/Users/mazaiting/Desktop/1.zip&quot;;</span><br><span class="line">    // 根据路径获取NSFileHandle, 它不会自动创建文件，而是第0个字节添加数据</span><br><span class="line">    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];</span><br><span class="line">    // 如果fileHandle存在，则让fileHandle的offset偏移量指向文件的末尾，进行数据的添加</span><br><span class="line">    // 如果fileHandle不存在，则创建文件</span><br><span class="line">    if (fileHandle) &#123;</span><br><span class="line">        // fileHandle存在</span><br><span class="line">        // 将文件指针指向文件的末尾</span><br><span class="line">        [fileHandle seekToEndOfFile];</span><br><span class="line">        // 写数据</span><br><span class="line">        [fileHandle writeData:data];</span><br><span class="line">        // 关闭文件</span><br><span class="line">        [fileHandle closeFile];</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // fileHandle不存在</span><br><span class="line">        [data writeToFile:filePath atomically:YES];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>####5.  下载回调设置<br>MTDownloader.h 中在download方法中增加成功、进度、失败的对调block。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">#import &lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">@interface MTDownloader : NSObject</span><br><span class="line">// 下载方法</span><br><span class="line">// netUrl 下载的网络连接</span><br><span class="line">// successBlock 成功回调block</span><br><span class="line">// processBlock 进度对调block</span><br><span class="line">// errorBlock 异常回调block</span><br><span class="line">- (void)download:(NSString *)netUrl successBlock:(void(^)(NSString *path))successBlock processBlock:(void(^)(float process))processBlock errorBlock:(void(^)(NSError *error))errorBlock;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>MTDownloader.m 中实现该方法，并将下载文件的操作重新开启一个新的线程来执行下载任务。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br></pre></td><td class="code"><pre><span class="line">//</span><br><span class="line">// 断点续传思路</span><br><span class="line">// 1. 首先发送一个head请求，获取到服务器文件的大小和名称</span><br><span class="line">// 2. 判断本地文件是否存在</span><br><span class="line">//      1). 不存在，从0开始下载</span><br><span class="line">//      2). 存在</span><br><span class="line">//          a. 本地文件大小 == 服务器文件大小  不需要下载</span><br><span class="line">//          b. 本地文件大小 &lt; 服务器文件大小   从当前位置下载</span><br><span class="line">//          c. 本地文件打下 &gt; 服务器文件大小   删除文件，从0下载</span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">// 分类</span><br><span class="line">@interface MTDownloader () &lt;NSURLConnectionDataDelegate&gt;</span><br><span class="line">// 记录文件的总长度,因为在获取下载进度的时候需要文件总长度，所以定义为属性</span><br><span class="line">@property (nonatomic, assign) long long expectedContentLength;</span><br><span class="line">// 记录当前文件的长度</span><br><span class="line">@property (nonatomic, assign) long long currentFileSize;</span><br><span class="line">// NSOutputStream用来保存每次下载的二进制数据</span><br><span class="line">@property (nonatomic, strong) NSOutputStream *outputStream;</span><br><span class="line">// 文件的存储路径</span><br><span class="line">@property (nonatomic, strong) NSString *filePath;</span><br><span class="line">// 下载成功后的回调</span><br><span class="line">@property (nonatomic, copy) void (^successBlock)(NSString *path);</span><br><span class="line">// 下载进度回调</span><br><span class="line">@property (nonatomic, copy) void (^processBlock)(float process);</span><br><span class="line">// 下载异常的回调</span><br><span class="line">@property (nonatomic, copy) void (^errorBlock)(NSError *error);</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloader</span><br><span class="line">// 下载</span><br><span class="line">- (void)download:(NSString *)netUrl successBlock:(void (^)(NSString *))successBlock processBlock:(void (^)(float))processBlock errorBlock:(void (^)(NSError *))errorBlock &#123;</span><br><span class="line">    self.successBlock = successBlock;</span><br><span class="line">    self.processBlock = processBlock;</span><br><span class="line">    self.errorBlock = errorBlock;</span><br><span class="line">    </span><br><span class="line">    // 创建url</span><br><span class="line">    NSURL *url = [NSURL URLWithString:netUrl];</span><br><span class="line">    // 获取服务器文件信息, 获取当前文件长度</span><br><span class="line">    [self getServerFileInfo:url];</span><br><span class="line">    // 获取本地文件信息，并且和服务器做比较</span><br><span class="line">    self.currentFileSize = [self getLocalFileInfo];</span><br><span class="line">    // 判断当前文件大小是否是-1，如果是-1，说明文件已经下载完成</span><br><span class="line">    if (self.currentFileSize == -1) &#123;</span><br><span class="line">//        NSLog(@&quot;文件已下载完成，请不要重复下载!!!&quot;);</span><br><span class="line">        // 如果下载回调不为空</span><br><span class="line">        if (self.successBlock) &#123;</span><br><span class="line">            // 分发消息到主线程，让主线程来处理</span><br><span class="line">            dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">                self.successBlock(self.filePath);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    // 从指定位置处下载文件</span><br><span class="line">    [self downloadFile: url];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 从指定位置处下载文件</span><br><span class="line">- (void)downloadFile:(NSURL *)url &#123;</span><br><span class="line">    // 创建一个新的线程，并添加到队列中</span><br><span class="line">    [[NSOperationQueue new] addOperationWithBlock:^&#123;</span><br><span class="line">        // 创建一个请求</span><br><span class="line">        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];</span><br><span class="line">        // 请求头</span><br><span class="line">        // Range:bytes=x-y 从x个字节下载到y个字节</span><br><span class="line">        // Range:bytes=x-  从x个字节下载到最后</span><br><span class="line">        // Range:bytes=-y  从开始下载到y个字节</span><br><span class="line">        [request setValue:[NSString stringWithFormat:@&quot;bytes=%lld-&quot;, self.currentFileSize] forHTTPHeaderField:@&quot;Range&quot;];</span><br><span class="line">        </span><br><span class="line">        // 设置代理, 实现NSURLConnectionDataDelegate协议</span><br><span class="line">        [[NSURLConnection alloc] initWithRequest:request delegate:self];</span><br><span class="line">        // 开启消息循环</span><br><span class="line">        [[NSRunLoop currentRunLoop] run];</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 检测本地文件大小</span><br><span class="line">- (long long)getLocalFileInfo &#123;</span><br><span class="line">    // 文件的长度， 如果文件不存在，则为0</span><br><span class="line">    long long fileSize = 0;</span><br><span class="line">    // 获取文件管理者对象</span><br><span class="line">    NSFileManager *fileManager = [NSFileManager defaultManager];</span><br><span class="line">    // 判断文件是否存在</span><br><span class="line">    if ([fileManager fileExistsAtPath:self.filePath]) &#123;</span><br><span class="line">        // 文件存在</span><br><span class="line">        // 获取本地文件的大小</span><br><span class="line">        NSDictionary *attrs = [fileManager attributesOfItemAtPath:self.filePath error:NULL];</span><br><span class="line">        // 赋值</span><br><span class="line">        fileSize = attrs.fileSize;</span><br><span class="line">        // 文件大小等于服务器文件长度</span><br><span class="line">        if (fileSize == self.expectedContentLength) &#123;</span><br><span class="line">            fileSize = -1;</span><br><span class="line">        &#125;</span><br><span class="line">        // 文件大小大于服务器文件长度</span><br><span class="line">        if (fileSize &gt; self.expectedContentLength) &#123;</span><br><span class="line">            fileSize = 0;</span><br><span class="line">            // 删除文件</span><br><span class="line">            [fileManager removeItemAtPath:self.filePath error:NULL];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return fileSize;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 获取服务器文件信息</span><br><span class="line">// 文件的url</span><br><span class="line">- (void)getServerFileInfo:(NSURL *)url &#123;</span><br><span class="line">    // 创建一个请求</span><br><span class="line">    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];</span><br><span class="line">    // 设置请求方法</span><br><span class="line">    request.HTTPMethod = @&quot;head&quot;;</span><br><span class="line">    // 同步请求响应体</span><br><span class="line">    NSURLResponse *response = nil;</span><br><span class="line">    // 发送一个同步请求</span><br><span class="line">    [NSURLConnection sendSynchronousRequest:request returningResponse:&amp;response error:NULL];</span><br><span class="line">    </span><br><span class="line">    // 设置文件的总长度，注意:在下载时- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;方法中为当前文件总长度赋值的语句要删除</span><br><span class="line">    self.expectedContentLength = response.expectedContentLength;</span><br><span class="line">    // 设置文件的存储路径, 存储在临时目录下，拼接文件名</span><br><span class="line">    self.filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:response.suggestedFilename];</span><br><span class="line">//    NSLog(@&quot;%@&quot;, self.filePath);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#pragma mark- 代理方法</span><br><span class="line">// 接收到响应头</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response &#123;</span><br><span class="line">//    NSLog(@&quot;接收到响应 %@&quot;, response);</span><br><span class="line">    // 接收到响应头的时候初始化outputStream</span><br><span class="line">    self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.filePath append:YES];</span><br><span class="line">    // 打开流</span><br><span class="line">    [self.outputStream open];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 接收到数据--一点点接收</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data &#123;</span><br><span class="line">    // 将每次接收到的字节长度与已有的文件长度相加</span><br><span class="line">    self.currentFileSize += data.length;</span><br><span class="line">    // 当前已下载的文件长度 * 1.0 / 文件的总长度 = 当前的进度</span><br><span class="line">    float process = self.currentFileSize * 1.0 / self.expectedContentLength;</span><br><span class="line">//    NSLog(@&quot;接收数据: %f&quot;, process);</span><br><span class="line">    // 保存数据</span><br><span class="line">    [self saveData:data];</span><br><span class="line">    // 判断进度回调是否为空</span><br><span class="line">    if (self.processBlock) &#123;</span><br><span class="line">        // 如果不为空则回到主线程</span><br><span class="line">        dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">            self.processBlock(process);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载完成</span><br><span class="line">- (void)connectionDidFinishLoading:(NSURLConnection *)connection &#123;</span><br><span class="line">//    NSLog(@&quot;下载完成&quot;);</span><br><span class="line">    // 下载完成的时候，关闭流</span><br><span class="line">    [self.outputStream close];</span><br><span class="line">    </span><br><span class="line">    // 如果下载回调不为空</span><br><span class="line">    if (self.successBlock) &#123;</span><br><span class="line">        // 分发消息到主线程，让主线程来处理</span><br><span class="line">        dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">            self.successBlock(self.filePath);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载出错</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error &#123;</span><br><span class="line">//    NSLog(@&quot;下载出错&quot;);</span><br><span class="line">    // 判断流是否为空，下载出错的时候，关闭流</span><br><span class="line">    if (self.outputStream) &#123;</span><br><span class="line">        [self.outputStream close];</span><br><span class="line">    &#125;</span><br><span class="line">    // 判断异常回调是否为空</span><br><span class="line">    if (self.errorBlock) &#123;</span><br><span class="line">        // 不为空回到主线程</span><br><span class="line">        dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">            self.errorBlock(error);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSOutputStream保存数据</span><br><span class="line">// data 每次下载的二进制文件</span><br><span class="line">- (void)saveData:(NSData *)data &#123;</span><br><span class="line">    // 写数据</span><br><span class="line">    [self.outputStream write:data.bytes maxLength:data.length];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSFileHandle保存数据</span><br><span class="line">// data 每次下载的二进制数据</span><br><span class="line">- (void)saveData1:(NSData *)data &#123;</span><br><span class="line">    // 保存文件的路径</span><br><span class="line">    NSString *filePath = @&quot;/Users/mazaiting/Desktop/1.zip&quot;;</span><br><span class="line">    // 根据路径获取NSFileHandle, 它不会自动创建文件，而是第0个字节添加数据</span><br><span class="line">    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];</span><br><span class="line">    // 如果fileHandle存在，则让fileHandle的offset偏移量指向文件的末尾，进行数据的添加</span><br><span class="line">    // 如果fileHandle不存在，则创建文件</span><br><span class="line">    if (fileHandle) &#123;</span><br><span class="line">        // fileHandle存在</span><br><span class="line">        // 将文件指针指向文件的末尾</span><br><span class="line">        [fileHandle seekToEndOfFile];</span><br><span class="line">        // 写数据</span><br><span class="line">        [fileHandle writeData:data];</span><br><span class="line">        // 关闭文件</span><br><span class="line">        [fileHandle closeFile];</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // fileHandle不存在</span><br><span class="line">        [data writeToFile:filePath atomically:YES];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>ViewController.m中的调用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;ViewController.h&quot;</span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">@interface ViewController ()</span><br><span class="line"></span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation ViewController</span><br><span class="line"></span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">    [super viewDidLoad];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)touchesBegan:(NSSet&lt;UITouch *&gt; *)touches withEvent:(UIEvent *)event &#123;</span><br><span class="line">    MTDownloader *downloader = [MTDownloader new];</span><br><span class="line">    NSString *url = @&quot;http://127.0.0.1/HBuilder.zip&quot;;</span><br><span class="line">    [downloader download:url successBlock:^(NSString *path) &#123;</span><br><span class="line">        NSLog(@&quot;下载成功&quot;);</span><br><span class="line">    &#125; processBlock:^(float process) &#123;</span><br><span class="line">        NSLog(@&quot;下载进度: %f&quot;, process);</span><br><span class="line">    &#125; errorBlock:^(NSError *error) &#123;</span><br><span class="line">        NSLog(@&quot;下载出错 %@&quot;, error);</span><br><span class="line">    &#125;];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>####6. 进度条显示— <a href="http://www.jianshu.com/p/466f3bab502b" target="_blank" rel="noopener">自定义圆形进度条</a><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;ViewController.h&quot;</span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">#import &quot;MTProcessView.h&quot;</span><br><span class="line">@interface ViewController ()</span><br><span class="line">@property (weak, nonatomic) IBOutlet MTProcessView *processView;</span><br><span class="line"></span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation ViewController</span><br><span class="line"></span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">    [super viewDidLoad];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)touchesBegan:(NSSet&lt;UITouch *&gt; *)touches withEvent:(UIEvent *)event &#123;</span><br><span class="line">    MTDownloader *downloader = [MTDownloader new];</span><br><span class="line">    NSString *url = @&quot;http://127.0.0.1/HBuilder.zip&quot;;</span><br><span class="line">    [downloader download:url successBlock:^(NSString *path) &#123;</span><br><span class="line">        NSLog(@&quot;下载成功&quot;);</span><br><span class="line">    &#125; processBlock:^(float process) &#123;</span><br><span class="line">        self.processView.process = process;</span><br><span class="line">        NSLog(@&quot;下载进度: %f&quot;, process);</span><br><span class="line">    &#125; errorBlock:^(NSError *error) &#123;</span><br><span class="line">        NSLog(@&quot;下载出错 %@&quot;, error);</span><br><span class="line">    &#125;];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>####7.  暂停下载<br>在MTDownloader.h中添加暂停下载方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#import &lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">@interface MTDownloader : NSObject</span><br><span class="line">// ... 省略其他方法</span><br><span class="line">// 暂停下载</span><br><span class="line">- (void)pause;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>在MTDownloader.m中实现该方法， 以下内容为该类修改的方法。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">// 分类</span><br><span class="line">@interface MTDownloader () &lt;NSURLConnectionDataDelegate&gt;</span><br><span class="line">// 下载时创建的NSURLConnection，可用于取消下载</span><br><span class="line">@property (nonatomic, strong) NSURLConnection *urlConnection;</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloader</span><br><span class="line">// 从指定位置处下载文件</span><br><span class="line">- (void)downloadFile:(NSURL *)url &#123;</span><br><span class="line">    // 创建一个新的线程，并添加到队列中</span><br><span class="line">    [[NSOperationQueue new] addOperationWithBlock:^&#123;</span><br><span class="line">        // 创建一个请求</span><br><span class="line">        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];</span><br><span class="line">        // 请求头</span><br><span class="line">        // Range:bytes=x-y 从x个字节下载到y个字节</span><br><span class="line">        // Range:bytes=x-  从x个字节下载到最后</span><br><span class="line">        // Range:bytes=-y  从开始下载到y个字节</span><br><span class="line">        [request setValue:[NSString stringWithFormat:@&quot;bytes=%lld-&quot;, self.currentFileSize] forHTTPHeaderField:@&quot;Range&quot;];</span><br><span class="line">        </span><br><span class="line">        // 设置代理, 实现NSURLConnectionDataDelegate协议</span><br><span class="line">        self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];</span><br><span class="line">        // 开启消息循环</span><br><span class="line">        [[NSRunLoop currentRunLoop] run];</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line">// 暂停下载</span><br><span class="line">- (void)pause &#123;</span><br><span class="line">    // 取消下载</span><br><span class="line">    [self.urlConnection cancel];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>####8. 下载类的封装<br>MTDownloadManager.h<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">#import &lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">@interface MTDownloadManager : NSObject</span><br><span class="line">// 单例</span><br><span class="line">+ (instancetype)sharedManager;</span><br><span class="line">// 下载方法</span><br><span class="line">// netUrl 下载的网络连接</span><br><span class="line">// successBlock 成功回调block</span><br><span class="line">// processBlock 进度对调block</span><br><span class="line">// errorBlock 异常回调block</span><br><span class="line">- (void)download:(NSString *)netUrl successBlock:(void(^)(NSString *path))successBlock processBlock:(void(^)(float process))processBlock errorBlock:(void(^)(NSError *error))errorBlock;</span><br><span class="line"></span><br><span class="line">// 暂停下载</span><br><span class="line">- (void)pause:(NSString *)netUrl;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>MTDownloadManager.m<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;MTDownloadManager.h&quot;</span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line"></span><br><span class="line">@interface MTDownloadManager ()</span><br><span class="line">// 下载操作缓存池</span><br><span class="line">@property (nonatomic, strong) NSMutableDictionary *downloadCache;</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloadManager</span><br><span class="line">// 单例</span><br><span class="line">+ (instancetype)sharedManager &#123;</span><br><span class="line">    static id instance = nil;</span><br><span class="line">    </span><br><span class="line">    static dispatch_once_t onceToken;</span><br><span class="line">    dispatch_once(&amp;onceToken, ^&#123;</span><br><span class="line">        instance = [self new];</span><br><span class="line">    &#125;);</span><br><span class="line">    return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 懒加载</span><br><span class="line">- (NSMutableDictionary *)downloadCache &#123;</span><br><span class="line">    if (_downloadCache == nil) &#123;</span><br><span class="line">        _downloadCache = [NSMutableDictionary dictionaryWithCapacity:10];</span><br><span class="line">    &#125;</span><br><span class="line">    return _downloadCache;</span><br><span class="line">&#125;</span><br><span class="line">// 下载</span><br><span class="line">- (void)download:(NSString *)netUrl successBlock:(void (^)(NSString *))successBlock processBlock:(void (^)(float))processBlock errorBlock:(void (^)(NSError *))errorBlock &#123;</span><br><span class="line">    // 判断缓存池中是否有下载操作</span><br><span class="line">    if (self.downloadCache[netUrl]) &#123;</span><br><span class="line">        NSLog(@&quot;正在拼命下载中...&quot;);</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    // 新建下载</span><br><span class="line">    MTDownloader *downloader = [MTDownloader download:netUrl successBlock:^(NSString *path) &#123;</span><br><span class="line">        // 移除下载操作</span><br><span class="line">        [self.downloadCache removeObjectForKey:netUrl];</span><br><span class="line">        if (successBlock) &#123;</span><br><span class="line">            successBlock(path);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; processBlock:processBlock errorBlock:^(NSError *error) &#123;</span><br><span class="line">        // 移除下载操作</span><br><span class="line">        [self.downloadCache removeObjectForKey:netUrl];</span><br><span class="line">        if (errorBlock) &#123;</span><br><span class="line">            errorBlock(error);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;];</span><br><span class="line">    [[NSOperationQueue new] addOperation:downloader];</span><br><span class="line">    </span><br><span class="line">    // 添加到缓存池中</span><br><span class="line">    [self.downloadCache setObject:downloader forKey:netUrl];</span><br><span class="line">&#125;</span><br><span class="line">// 暂停</span><br><span class="line">- (void)pause:(NSString *)netUrl &#123;</span><br><span class="line">    MTDownloader *downloader = self.downloadCache[netUrl];</span><br><span class="line">    // 判断是否为空，如果不为空，则暂停；如果为空，则什么都不做</span><br><span class="line">    if (downloader == nil) &#123;</span><br><span class="line">        NSLog(@&quot;没有下载操作，无法暂停&quot;);</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    [downloader pause];</span><br><span class="line">    </span><br><span class="line">    // 删除缓存池中的下载操作</span><br><span class="line">    [self.downloadCache removeObjectForKey:netUrl];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>MTDownloader.h<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">#import &lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">@interface MTDownloader : NSOperation</span><br><span class="line">// 下载方法</span><br><span class="line">// netUrl 下载的网络连接</span><br><span class="line">// successBlock 成功回调block</span><br><span class="line">// processBlock 进度对调block</span><br><span class="line">// errorBlock 异常回调block</span><br><span class="line">+ (instancetype)download:(NSString *)netUrl successBlock:(void(^)(NSString *path))successBlock processBlock:(void(^)(float process))processBlock errorBlock:(void(^)(NSError *error))errorBlock;</span><br><span class="line"></span><br><span class="line">// 暂停下载</span><br><span class="line">- (void)pause;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p>MTDownloader.m<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br></pre></td><td class="code"><pre><span class="line">// 断点续传思路</span><br><span class="line">// 1. 首先发送一个head请求，获取到服务器文件的大小和名称</span><br><span class="line">// 2. 判断本地文件是否存在</span><br><span class="line">//      1). 不存在，从0开始下载</span><br><span class="line">//      2). 存在</span><br><span class="line">//          a. 本地文件大小 == 服务器文件大小  不需要下载</span><br><span class="line">//          b. 本地文件大小 &lt; 服务器文件大小   从当前位置下载</span><br><span class="line">//          c. 本地文件打下 &gt; 服务器文件大小   删除文件，从0下载</span><br><span class="line">#import &quot;MTDownloader.h&quot;</span><br><span class="line">// 分类</span><br><span class="line">@interface MTDownloader () &lt;NSURLConnectionDataDelegate&gt;</span><br><span class="line">// 记录文件的总长度,因为在获取下载进度的时候需要文件总长度，所以定义为属性</span><br><span class="line">@property (nonatomic, assign) long long expectedContentLength;</span><br><span class="line">// 记录当前文件的长度</span><br><span class="line">@property (nonatomic, assign) long long currentFileSize;</span><br><span class="line">// NSOutputStream用来保存每次下载的二进制数据</span><br><span class="line">@property (nonatomic, strong) NSOutputStream *outputStream;</span><br><span class="line">// 下载时创建的NSURLConnection，可用于取消下载</span><br><span class="line">@property (nonatomic, strong) NSURLConnection *urlConnection;</span><br><span class="line">// 文件的存储路径</span><br><span class="line">@property (nonatomic, strong) NSString *filePath;</span><br><span class="line">// 下载成功后的回调</span><br><span class="line">@property (nonatomic, copy) void (^successBlock)(NSString *path);</span><br><span class="line">// 下载进度回调</span><br><span class="line">@property (nonatomic, copy) void (^processBlock)(float process);</span><br><span class="line">// 下载异常的回调</span><br><span class="line">@property (nonatomic, copy) void (^errorBlock)(NSError *error);</span><br><span class="line">// 下载链接</span><br><span class="line">@property (nonatomic, copy) NSString *urlString;</span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation MTDownloader</span><br><span class="line">// 下载</span><br><span class="line">+ (instancetype)download:(NSString *)netUrl successBlock:(void (^)(NSString *))successBlock processBlock:(void (^)(float))processBlock errorBlock:(void (^)(NSError *))errorBlock &#123;</span><br><span class="line">    MTDownloader *downloader = [MTDownloader new];</span><br><span class="line">    downloader.successBlock = successBlock;</span><br><span class="line">    downloader.processBlock = processBlock;</span><br><span class="line">    downloader.errorBlock = errorBlock;</span><br><span class="line">    downloader.urlString = netUrl;</span><br><span class="line">    return downloader;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)main &#123;</span><br><span class="line">    @autoreleasepool &#123;</span><br><span class="line">        // 创建url</span><br><span class="line">        NSURL *url = [NSURL URLWithString:self.urlString];</span><br><span class="line">        // 获取服务器文件信息, 获取当前文件长度</span><br><span class="line">        [self getServerFileInfo:url];</span><br><span class="line">        // 获取本地文件信息，并且和服务器做比较</span><br><span class="line">        self.currentFileSize = [self getLocalFileInfo];</span><br><span class="line">        // 判断当前文件大小是否是-1，如果是-1，说明文件已经下载完成</span><br><span class="line">        if (self.currentFileSize == -1) &#123;</span><br><span class="line">            //        NSLog(@&quot;文件已下载完成，请不要重复下载!!!&quot;);</span><br><span class="line">            // 如果下载回调不为空</span><br><span class="line">            if (self.successBlock) &#123;</span><br><span class="line">                // 分发消息到主线程，让主线程来处理</span><br><span class="line">                dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">                    self.successBlock(self.filePath);</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        // 从指定位置处下载文件</span><br><span class="line">        [self downloadFile: url];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 从指定位置处下载文件</span><br><span class="line">- (void)downloadFile:(NSURL *)url &#123;</span><br><span class="line">    // 创建一个新的线程，并添加到队列中</span><br><span class="line">    [[NSOperationQueue new] addOperationWithBlock:^&#123;</span><br><span class="line">        // 创建一个请求</span><br><span class="line">        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];</span><br><span class="line">        // 请求头</span><br><span class="line">        // Range:bytes=x-y 从x个字节下载到y个字节</span><br><span class="line">        // Range:bytes=x-  从x个字节下载到最后</span><br><span class="line">        // Range:bytes=-y  从开始下载到y个字节</span><br><span class="line">        [request setValue:[NSString stringWithFormat:@&quot;bytes=%lld-&quot;, self.currentFileSize] forHTTPHeaderField:@&quot;Range&quot;];</span><br><span class="line">        </span><br><span class="line">        // 设置代理, 实现NSURLConnectionDataDelegate协议</span><br><span class="line">        self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];</span><br><span class="line">        // 开启消息循环</span><br><span class="line">        [[NSRunLoop currentRunLoop] run];</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 检测本地文件大小</span><br><span class="line">- (long long)getLocalFileInfo &#123;</span><br><span class="line">    // 文件的长度， 如果文件不存在，则为0</span><br><span class="line">    long long fileSize = 0;</span><br><span class="line">    // 获取文件管理者对象</span><br><span class="line">    NSFileManager *fileManager = [NSFileManager defaultManager];</span><br><span class="line">    // 判断文件是否存在</span><br><span class="line">    if ([fileManager fileExistsAtPath:self.filePath]) &#123;</span><br><span class="line">        // 文件存在</span><br><span class="line">        // 获取本地文件的大小</span><br><span class="line">        NSDictionary *attrs = [fileManager attributesOfItemAtPath:self.filePath error:NULL];</span><br><span class="line">        // 赋值</span><br><span class="line">        fileSize = attrs.fileSize;</span><br><span class="line">        // 文件大小等于服务器文件长度</span><br><span class="line">        if (fileSize == self.expectedContentLength) &#123;</span><br><span class="line">            fileSize = -1;</span><br><span class="line">        &#125;</span><br><span class="line">        // 文件大小大于服务器文件长度</span><br><span class="line">        if (fileSize &gt; self.expectedContentLength) &#123;</span><br><span class="line">            fileSize = 0;</span><br><span class="line">            // 删除文件</span><br><span class="line">            [fileManager removeItemAtPath:self.filePath error:NULL];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return fileSize;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 获取服务器文件信息</span><br><span class="line">// 文件的url</span><br><span class="line">- (void)getServerFileInfo:(NSURL *)url &#123;</span><br><span class="line">    // 创建一个请求</span><br><span class="line">    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];</span><br><span class="line">    // 设置请求方法</span><br><span class="line">    request.HTTPMethod = @&quot;head&quot;;</span><br><span class="line">    // 同步请求响应体</span><br><span class="line">    NSURLResponse *response = nil;</span><br><span class="line">    // 发送一个同步请求</span><br><span class="line">    [NSURLConnection sendSynchronousRequest:request returningResponse:&amp;response error:NULL];</span><br><span class="line">    </span><br><span class="line">    // 设置文件的总长度，注意:在下载时- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;方法中为当前文件总长度赋值的语句要删除</span><br><span class="line">    self.expectedContentLength = response.expectedContentLength;</span><br><span class="line">    // 设置文件的存储路径, 存储在临时目录下，拼接文件名</span><br><span class="line">    self.filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:response.suggestedFilename];</span><br><span class="line">//    NSLog(@&quot;%@&quot;, self.filePath);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 暂停下载</span><br><span class="line">- (void)pause &#123;</span><br><span class="line">    // 取消下载</span><br><span class="line">    [self.urlConnection cancel];</span><br><span class="line">    // 取消自定义操作</span><br><span class="line">    [self cancel];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#pragma mark- 代理方法</span><br><span class="line">// 接收到响应头</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response &#123;</span><br><span class="line">//    NSLog(@&quot;接收到响应 %@&quot;, response);</span><br><span class="line">    // 接收到响应头的时候初始化outputStream</span><br><span class="line">    self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.filePath append:YES];</span><br><span class="line">    // 打开流</span><br><span class="line">    [self.outputStream open];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 接收到数据--一点点接收</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data &#123;</span><br><span class="line">    // 将每次接收到的字节长度与已有的文件长度相加</span><br><span class="line">    self.currentFileSize += data.length;</span><br><span class="line">    // 当前已下载的文件长度 * 1.0 / 文件的总长度 = 当前的进度</span><br><span class="line">    float process = self.currentFileSize * 1.0 / self.expectedContentLength;</span><br><span class="line">//    NSLog(@&quot;接收数据: %f&quot;, process);</span><br><span class="line">    // 保存数据</span><br><span class="line">    [self saveData:data];</span><br><span class="line">    // 判断进度回调是否为空</span><br><span class="line">    if (self.processBlock) &#123;</span><br><span class="line">        // 如果不为空则回到主线程</span><br><span class="line">        dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">            self.processBlock(process);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载完成</span><br><span class="line">- (void)connectionDidFinishLoading:(NSURLConnection *)connection &#123;</span><br><span class="line">//    NSLog(@&quot;下载完成&quot;);</span><br><span class="line">    // 下载完成的时候，关闭流</span><br><span class="line">    [self.outputStream close];</span><br><span class="line">    </span><br><span class="line">    // 如果下载回调不为空</span><br><span class="line">    if (self.successBlock) &#123;</span><br><span class="line">        // 分发消息到主线程，让主线程来处理</span><br><span class="line">        dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">            self.successBlock(self.filePath);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 下载出错</span><br><span class="line">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error &#123;</span><br><span class="line">//    NSLog(@&quot;下载出错&quot;);</span><br><span class="line">    // 判断流是否为空，下载出错的时候，关闭流</span><br><span class="line">    if (self.outputStream) &#123;</span><br><span class="line">        [self.outputStream close];</span><br><span class="line">    &#125;</span><br><span class="line">    // 判断异常回调是否为空</span><br><span class="line">    if (self.errorBlock) &#123;</span><br><span class="line">        // 不为空回到主线程</span><br><span class="line">        dispatch_async(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">            self.errorBlock(error);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSOutputStream保存数据</span><br><span class="line">// data 每次下载的二进制文件</span><br><span class="line">- (void)saveData:(NSData *)data &#123;</span><br><span class="line">    // 写数据</span><br><span class="line">    [self.outputStream write:data.bytes maxLength:data.length];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// NSFileHandle保存数据</span><br><span class="line">// data 每次下载的二进制数据</span><br><span class="line">- (void)saveData1:(NSData *)data &#123;</span><br><span class="line">    // 保存文件的路径</span><br><span class="line">    NSString *filePath = @&quot;/Users/mazaiting/Desktop/1.zip&quot;;</span><br><span class="line">    // 根据路径获取NSFileHandle, 它不会自动创建文件，而是第0个字节添加数据</span><br><span class="line">    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];</span><br><span class="line">    // 如果fileHandle存在，则让fileHandle的offset偏移量指向文件的末尾，进行数据的添加</span><br><span class="line">    // 如果fileHandle不存在，则创建文件</span><br><span class="line">    if (fileHandle) &#123;</span><br><span class="line">        // fileHandle存在</span><br><span class="line">        // 将文件指针指向文件的末尾</span><br><span class="line">        [fileHandle seekToEndOfFile];</span><br><span class="line">        // 写数据</span><br><span class="line">        [fileHandle writeData:data];</span><br><span class="line">        // 关闭文件</span><br><span class="line">        [fileHandle closeFile];</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // fileHandle不存在</span><br><span class="line">        [data writeToFile:filePath atomically:YES];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure></p>
<p><img src="http://upload-images.jianshu.io/upload_images/3110861-42f511634a28dc33.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="效果图.png"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/IM/XMPPFramework-使用(Mac)/" rel="next" title="XMPPFramework-使用(Mac)">
                <i class="fa fa-chevron-left"></i> XMPPFramework-使用(Mac)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/iOS/iOS-GET-POST请求/" rel="prev" title="iOS-GET-POST请求">
                iOS-GET-POST请求 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
